CREATE PROCEDURE sp_ThemCTHoaDon
	@MaHD int,
	@MaP int,
	@DonGia money,
	@NgayThanhToan datetime,
	@NgayThue datetime
AS
BEGIN TRAN
	if not exists(SELECT * FROM HOADON WHERE MaHD = @MaHD)
	begin
		raiserror('Hoa don chua ton tai',16,1)
		rollback
		return
	end

	if not exists(SELECT * FROM PHONG WHERE ID_Phong = @MaP)
	begin
		raiserror('Phong chua ton tai',16,1)
		rollback
		return
	end

	declare @MaCTHD int
	set @MaCTHD = 1
	
	while exists (SELECT * FROM CT_HOADON WHERE MaCTHD = @MaCTHD)
		set @MaCTHD = @MaCTHD + 1

	declare @SoNgayThue int
	set @SoNgayThue = datediff(dd,@NgayThue, @NgayThanhToan)

	if(@SoNgayThue = 0)
		Set @SoNgayThue = 1

	declare @ThanhTien money
	set @ThanhTien = @SoNgayThue * @DonGia

	INSERT INTO CT_HOADON VALUES(@MaCTHD, @MaHD, @MaP, @DonGia, @SoNgayThue, @ThanhTien)
	UPDATE PHONG SET MaTinhTrang = 1 WHERE ID_Phong = @MaP
	if(@@error <> 0)
	begin
		raiserror('Them Chi tiet hoa don that bai', 16,1)
		rollback
	end
COMMIT